package com.fin.quant.web.service.realtime;

import com.fin.quant.web.utils.JsonUtils;
import com.fin.quant.web.vo.Stock;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.Map;

@Service
public class StockRTPriceService {

    private final RestTemplate restTemplate = new RestTemplate();


    /**
     * 获取股票实时价格
     *
     * @param stockCode
     * @return
     */
    public float getStockPrice(String stockCode) {
        return getStock(stockCode).getPrice().floatValue();
    }

    public Stock getStock(String stockCode) {
        String callback = "_ntes_quote_callback90445494";
        ResponseEntity<String> forEntity = restTemplate.getForEntity("http://api.money.126.net/data/feed/0{stockCode},money.api?callback={callback}", String.class, stockCode, callback);
        String body = forEntity.getBody();
        String jsonParsableResult = StringUtils.substring(body.replaceAll(callback, ""), 1, -2);
        System.out.println(jsonParsableResult);
        Map map = JsonUtils.toMapObject(jsonParsableResult);
        Map valueMap = ((Map) map.get("0" + stockCode));

        Stock stock = new Stock();
        stock.setPrice((double) valueMap.get("price"));
        stock.setName(String.valueOf(valueMap.get("name")));
        return stock;
    }

    public static void main(String[] args) {
        System.out.println(new StockRTPriceService().getStock("600036"));
    }

}
